package com.cnjson.sensor.protocolARP.waterQualitySensorProtocol.loader;

import com.cnjson.sensor.db.dao.EquipmeDao;
import com.cnjson.sensor.db.dao.EquipmeStateDao;
import com.cnjson.sensor.db.entity.EquipmentState;
import com.cnjson.sensor.db.utils.IdWorker;
import com.cnjson.sensor.protocolARP.waterQualitySensorProtocol.WaterQualitySensorResolveInterface;
import com.cnjson.sensor.protocolARP.waterQualitySensorProtocol.response.WaterQualitySensorResponse;
import com.cnjson.sensor.util.ByteUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.nio.channels.SocketChannel;
import java.util.Date;
@Component
public class Load implements WaterQualitySensorResolveInterface {
    private static final Logger logger = LoggerFactory.getLogger(Load.class);

   @Autowired
   private EquipmeStateDao equipmeStateDao;
   @Autowired
   private EquipmeDao equipmeDao;
   @Autowired
   private IdWorker idWorker;


    @Override
    public byte[] resolve(String[] data, SocketChannel client) {
        logger.info(Thread.currentThread().getId() +"设备登录中");

        byte[] response = null;
        try {
            // 2位设备地址段
            String address =data[7]+data[8];
            String equipmentStatusId = equipmeStateDao.findIdByEquipmentId(address);//根据equipment_id获取当前设备状态记录（ift_equipment_status）的id

            boolean isExistEquipment = equipmeDao.existsByNumber(address);//根据number字段(设备地址)查询设备表(ift_equipment)，确认设备存在
            //设备是否存在 address为设备编号
            //如果设备信息不存在数据库表中，在登录的请求里，response会有返回
            if (isExistEquipment) {

                String remote = client.getRemoteAddress().toString();
                if (equipmentStatusId!=null) {//说明当前设备状态存在
                    EquipmentState eq = new EquipmentState(equipmentStatusId);
                    eq.setEquipmentId(address);//设置设备的equipment_id
                    eq.setRunningState("1");
                    eq.setRemoteAddress(remote);
                    equipmeStateDao.save(eq);//根据equipment_id更新设备状态数据
                } else {
                    Date date = new Date();
                    EquipmentState e = new EquipmentState(idWorker.nextId()+"", address, "1", date, date,
                            date, date, "0", remote);
                    equipmeStateDao.save(e);
                }
            }

            logger.info("---------0x41 设备登录注册-------------地址-----------------" + address);

            if (isExistEquipment) {
                logger.info("---------0x41 设备登录注册-------------");
            } else {
                logger.warn("---------0x41 设备未配置-------------");
            }

            //4位地址
            String device=data[7]+data[8]+data[9]+data[10];
            byte[] deviceBytes= ByteUtils.hexStringToBytes(device);

            response = WaterQualitySensorResponse.buildRegisterPackage(deviceBytes, isExistEquipment);
        } catch (Exception e) {
            logger.error("----------0x41-----------" + e.getMessage());
        }
        return response;
    }
}
